package com.liao.badminton.code.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Enumeration;

public class WebUtil {
    private static Logger logger = LoggerFactory.getLogger(WebUtil.class);

    /**
     * 客户端返回JSON字符串
     *
     * @param response
     * @param object
     * @return
     */
    @SuppressWarnings("deprecation")
    public static void writeJson(HttpServletResponse response, Object object) {
        writeJson(response, JSON.toJSONString(object), MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

    /**
     * 客户端返回字符串
     *
     * @param response
     * @param string
     * @return
     */
    public static void writeJson(HttpServletResponse response, String string, String type) {
        try {
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            logger.error("", e);
        }
    }


    /**
     * 获取客户端真实ip
     *
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.indexOf(",") > 0) {
            logger.info(ip);
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            String[] ips = ip.split(",");
            for (String ip2 : ips) {
                String strIp = ip2;
                if (!"unknown".equalsIgnoreCase(strIp)) {
                    ip = strIp;
                    break;
                }
            }
        }
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            InetAddress inet = null;
            try { // 根据网卡取本机配置的IP
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                logger.error("getCurrentIP", e);
            }
            if (inet != null) {
                ip = inet.getHostAddress();
            }
        }
        logger.info("getRemoteAddr ip: " + ip);
        return ip;
    }
    public static String getClientPort(HttpServletRequest request) {
        return request.getHeader("X-Real-Port");

    }
    /**
     * 获取服务器IP地址
     *
     * @return
     */
    public static String getServerIp() {
        String SERVER_IP = null;
        try {
            if (SystemUtils.IS_OS_WINDOWS) {
                InetAddress address = InetAddress.getLocalHost();
                SERVER_IP = address.getHostAddress();
            } else {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                        .hasMoreElements(); ) {
                    NetworkInterface intf = en.nextElement();
                    String name = intf.getName();
                    if (!intf.isLoopback() && !intf.isVirtual() && intf.isUp()) {
                        Enumeration<InetAddress> addresses = intf.getInetAddresses();
                        while (addresses.hasMoreElements()) {
                            InetAddress ip = addresses.nextElement();
                            if (null != ip) {
                                return ip.getHostAddress();
                            }
                        }
                    }
                }
            }
            if (ObjectUtils.isEmpty(SERVER_IP)) {
                InetAddress address = InetAddress.getLocalHost();
                SERVER_IP = address.getHostAddress();
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return SERVER_IP;
    }

    public static String getServerName() {
        String SERVER_NAME = null;
        try {
            InetAddress address = InetAddress.getLocalHost();
            SERVER_NAME = address.getHostName();
        } catch (Exception e) {
            logger.error("", e);
        }
        return SERVER_NAME;
    }

    /*正则验证ip*/
    private static boolean checkIP(String ip) {
        return ip.matches("\\d{1,3}(\\.\\d{1,3}){3}");
    }

    public static void main(String[] args) {
        long remainTime = DateUtil.between(DateUtil.date(), DateUtil.endOfDay(new Date()), DateUnit.SECOND);
        System.out.println(DateUtil.date());
        System.out.println(DateUtil.endOfDay(new Date()));
        System.out.println(remainTime);
    }
}
